package com.atguigu.gmall.realtime.app.dwd.log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseAppV1;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.DateFormatUtil;
import com.atguigu.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @Author lzc
 * @Date 2022/4/29 14:45
 */
public class DWD_02_DwdTrafficUvDetailApp extends BaseAppV1 {
    public static void main(String[] args) {
        new DWD_02_DwdTrafficUvDetailApp()
            .init("DwdTrafficUvDetailApp",
                  3002,
                  1,
                  "DwdTrafficUvDetailApp",
                  "DwdTrafficUvDetailApp",
                  Constant.TOPIC_DWD_TRAFFIC_PAGE
            );
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        stream
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("ts"))
            )
            .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .process(new ProcessWindowFunction<JSONObject, String, String, TimeWindow>() {
                private ValueState<String> dateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    dateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("dateState", String.class));
                }
                
                @Override
                public void process(String key,
                                    Context ctx,
                                    Iterable<JSONObject> elements,
                                    Collector<String> out) throws Exception {
                    
                    // 今天
                    String today = DateFormatUtil.toDate(ctx.window().getStart());
                    String yesterday = dateState.value();
                    
                    if (!today.equals(yesterday)) {
                        dateState.clear();
                    }
                    
                    if (dateState.value() == null) {
                        
                        List<JSONObject> list = AtguiguUtil.toList(elements);
                        JSONObject min = Collections.min(list, Comparator.comparing(o -> o.getLong("ts")));
                        
                        String date = DateFormatUtil.toDate(min.getLong("ts"));
                        dateState.update(date);  // 状态中存储年月日
                        System.out.println(min);
                        out.collect(min.toJSONString());
                    }
                }
            })
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_UV_DETAIL));
        
    }
}
